package cn.zzq.shop.back.springmvc.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.zzq.shop.common.controller.BaseController;
import cn.zzq.shop.common.util.ConstatFinalUtil;
import cn.zzq.shop.common.util.PageInfoUtil;
import cn.zzq.shop.goods.pojo.AGoods;
import cn.zzq.shop.goods.pojo.AGoodsBrand;
import cn.zzq.shop.goods.pojo.AGoodsBrandEnum;
import cn.zzq.shop.goods.pojo.AGoodsCate;
import cn.zzq.shop.goods.service.IGoodsService;
import cn.zzq.shop.users.pojo.AAdmins;

/**
 * 不需要登陆就能访问的页面
 * @author WangshSxt
 *
 */
@Controller
@RequestMapping("/back/goods")
public class GoodsBackController extends BaseController
{
	@Resource
	private IGoodsService goodsService;
	
	/**
	 * 品牌模块开始
	 * @return
	 */
	/*打开品牌列表页面*/
	@RequestMapping("/brandList")
	public String brandList()
	{
		ConstatFinalUtil.SYS_LOGGER.info("--GoodsBackController--brandList-");
		return "/back/goods/brandList" ; 
	}
	
	/*返回品牌列表页面的json对象*/
	@RequestMapping(value="/brandListJSON",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String brandListJSON(String page,String rows){
		ConstatFinalUtil.SYS_LOGGER.info("----brandListJSON----");
		/*分页*/
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(page, rows);
		Map<String, Object> condMap = new HashMap<String, Object>();
		/*查询数据*/
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsBrandService(pageInfoUtil, condMap);
		List<AGoodsBrand> brandList = (List<AGoodsBrand>) resultMap.get("list");
		int totalRecord = Integer.valueOf(resultMap.get("totalRecord")+"");
		
		/*拼装json*/
		JSONObject resultJSON = new JSONObject();
		resultJSON.put("total", totalRecord);
		
		JSONArray dataArr = new JSONArray();
		/*循环往数组里面添加数据*/
		int count = 1;
		for (Iterator iterator = brandList.iterator(); iterator.hasNext();)
		{
			AGoodsBrand brand = (AGoodsBrand) iterator.next();
			/*brand对象变成json*/
			JSONObject brandJSON = brand.toJSON();
			brandJSON.put("count",count);
			
			dataArr.add(brandJSON);
			count ++;
		}
		resultJSON.put("rows", dataArr);
		return resultJSON.toJSONString();
	}
	
	/*打开添加品牌页面*/
	@RequestMapping("/brandInsert")
	public String brandInsert(){
		ConstatFinalUtil.SYS_LOGGER.info("----brandInsert----");
		
		return "/back/goods/brandInsert";
	}
	
	/*商品品牌添加提交*/
	@RequestMapping(value ="/brandInsertSubmit",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String brandInsertSubmit(HttpSession session,AGoodsBrand goodsBrand,MultipartFile file,String pubtimeStr){
		ConstatFinalUtil.SYS_LOGGER.info("-----brandInsertSubmit-----");
		ConstatFinalUtil.SYS_LOGGER.info("---file:{}--",file);
		
		/*判断文件是否为空*/
		if(file != null && !"".equalsIgnoreCase(file.getOriginalFilename())){
			/*原始文件名*/
			String originalFilename = file.getOriginalFilename();
			/*需要拼装的文件名*/
			String fileName = "";
			
			try
			{
				/* 上传的文件给上传到FTP中 */
				/*
				 * 三个路径的拼装:
				 * FTP路径:
				 * 相对路径:
				 * 网络路径:
				 * uploadfile/brand/2017-06-28/uuid.jpg
				 *  */
				String relaPath = ConstatFinalUtil.CONFIG_JSON.getString("relaPath");
				relaPath += "/brand/" + this.dateFormatUtil.dateStr(new Date()) + "/";
				/*uuid.拓展名*/
				fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
				
				/*调用FTPUtil*/
				boolean flag = this.ftpUtil.uploadFile(fileName, relaPath, file.getInputStream());
				if(flag){
					/*上传文件成功*/
					goodsBrand.setLogoPath(relaPath + fileName);
				}
			} catch (IOException e)
			{
				ConstatFinalUtil.SYS_LOGGER.error("---上传文件失败,文件名{}--",fileName,e);
			}
		}
		
		/*从session中获取用户对象*/
		AAdmins adminsSess = (AAdmins) session.getAttribute("admins");
		goodsBrand.setAdminsId(adminsSess.getId());
		/*时间自己手动赋值*/
		goodsBrand.setPubTime(this.dateFormatUtil.strDateTime(pubtimeStr));
		goodsBrand.setCreateTime(new Date());
		goodsBrand.setUpdateTime(new Date());
		
		JSONObject resultJOSN = this.goodsService.saveOneGoodsBrandService(goodsBrand);
		return resultJOSN.toJSONString();
	}
	
	/**
	 * 品牌模块结束 
	 */
	
	/**
	 * 商品模块开始
	 */
	/*打开商品列表页面*/
	@RequestMapping("/goodsList")
	public String goodsList(){
		ConstatFinalUtil.SYS_LOGGER.info("----goodsList-----");
		
		return "back/goods/goodsList";
	}
	
	/*查询商品列表页面JSON数据*/
	@RequestMapping(value="/goodsListJSON",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String goodsListJSON(String page,String rows,String keyword,String status,String st,String ed){
		ConstatFinalUtil.SYS_LOGGER.info("---goodsListJSON-----page{}",page);
		/*分页信息*/
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(page, rows);
		/*处理参数,搜索条件*/
		if(status == null){
			status = "";
		}
		if(st == null){
			st = "";
		}
		if(ed == null){
			ed = "";
		}
		
		/*搜索条件放入map*/
		Map<String, Object> condMap = new HashMap<>();
		Date stDate = null;
		Date edDate = null;
		if(!"".equalsIgnoreCase(st) && !"".equalsIgnoreCase(ed)){
			condMap.put("stDate", this.dateFormatUtil.strDateTime(st));
			condMap.put("edDate", this.dateFormatUtil.strDateTime(ed));
		}
		
		if(!"".equalsIgnoreCase(status)){
			condMap.put("status",status);
		}
				
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsService(pageInfoUtil, condMap);
		List<AGoods> goodsList = (List<AGoods>) resultMap.get("list");
		int totalRecord = Integer.valueOf(resultMap.get("totalRecord")+"");
		
		JSONObject resultJOSN = new JSONObject();
		resultJOSN.put("total", totalRecord);
		/*json数组*/
		JSONArray dataArr = new JSONArray();
		/*循环list,拼装json*/
		for (Iterator iterator = goodsList.iterator(); iterator.hasNext();)
		{
			AGoods goods = (AGoods) iterator.next();
			JSONObject goodJSON = goods.toJSON();
			dataArr.add(goodJSON);
		}
		resultJOSN.put("rows", dataArr);
		return resultJOSN.toJSONString();
	}
	
	
	/*
	 * 打开商品添加页面
	 * 需要列出分类的信息
	 * 树形结构
	 * */
	@RequestMapping("/goodsInsert")
	public String goodsInsert(Model model){
		ConstatFinalUtil.SYS_LOGGER.info("-----goodsInsert-----");
		Map<String, Object> condMap = new HashMap<>();
		
		/*查询所有启用的品牌*/
		condMap.clear();
		condMap.put("status", AGoodsBrandEnum.STATUS_ENABLE.getStatus());
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsCateService(null, condMap);
		List<AGoodsBrand> brandList = (List<AGoodsBrand>) resultMap.get("list");
		/*放到四大作用域*/
		model.addAttribute("brandList",brandList);
		
		/*查询分类*/
		List<AGoodsCate> goodsCateTreeList = this.goodsService.findTreeListCateService();
		/*放到四大作用域*/
		model.addAttribute("goodsCateTreeList",goodsCateTreeList);
		
		return "/back/goods/goodsInsert";
	}
	
	/*商品添加提交操作*/
	@RequestMapping("/goodsInsertSubmit")
	@ResponseBody
	public String goodsInsertSubmit(AGoods goods,HttpServletRequest request,String pubtimeStr,HttpSession session){
		ConstatFinalUtil.SYS_LOGGER.info("-----goodsInsertSubmit----");
		
		JSONObject resultJSON = new JSONObject();
		/*查询用户的分类*/
		Map<String, Object> condMap = new HashMap<>();
		condMap.put("id", goods.getCateId());
		AGoodsCate goodsCate = this.goodsService.findOneGoodsCateService(condMap);
		/*
		 * request.getParameter("spec_功能_制冷类型")
		 * [
				{
					"name": "功能",
					"keys": [
						{
							"name":"制冷类型",
							"values":"冷暖"
						}
					]
				}
			]
		 * */
		/*获取页面上用户选择的spec信息*/
		JSONArray specArr = goodsCate.getSpecArr();
		for (Iterator iterator = specArr.iterator(); iterator.hasNext();)
		{
			JSONObject jsonTemp = (JSONObject) iterator.next();
			JSONArray keysArr = (JSONArray) jsonTemp.get("keys");
			
			for (Iterator iterator2 = keysArr.iterator(); iterator2.hasNext();)
			{
				JSONObject keyJosnTemp = (JSONObject) iterator2.next();
				/*拼装jsp页面中的键*/
				String keyParam = "spec_" + jsonTemp.get("name") + "_" +keyJosnTemp.get("name");
				/*根据键获取相应的值*/
				String values = request.getParameter(keyParam);
				keyJosnTemp.put("values", values);
			}
		}
		
		goods.setSpec(specArr.toJSONString());
		goods.setPubTime(this.dateFormatUtil.strDateTime(pubtimeStr));
		
		AAdmins aAdmins = (AAdmins) session.getAttribute("admins");
		goods.setAdminsId(aAdmins.getId());
		goods.setCreateTime(new Date());
		goods.setUpdateTime(new Date());
		
		/*调用保存方法*/
		resultJSON = this.goodsService.saveOneGoodsService(goods);  
		return resultJSON.toJSONString();
	}
	
	
	
	
	
	
	
	
	
	
	/**
	 * 商品模块结束
	 */
}
